#!/usr/bin/python -O
# coding:utf8
__doc__ = 'Sdp entry file, all the start.'

import os
import sys
from lib.Public import Sysinfo, Time, Precheck, SOA
from lib.Config import LANG, WEBS, APPS
from lib.Web import StartWeb
from lib.App import StartApp
from lib import __version__


def SdpCloudRun(**kwargs):
    reload(sys)
    sys.setdefaultencoding(LANG)

    if not isinstance(kwargs, (dict)):
        raise('Bad Parameter, ask dict.')

    if kwargs['service'] in WEBS:
        StartWeb(**kwargs)

    elif kwargs['service'] in APPS:
        StartApp(**kwargs)

if __name__ == '__main__':

    user = SOA()
    Precheck(**user).checkargs()

    # check exec user is root?
    if os.geteuid() != 0:
        print "\033[0;31;40mAborting:this program must be run as root.\033[0m"
        sys.exit(1)

    try:
        SdpCloudRun(**user)
        print """\033[0;32;40mUser(%s, %s, %s) build sucessfully.
    CreateTime      => %s
    ExpireTime      => %s
    Hostname        => %s
    Sdp Version     => %s
    Kernel Version  => %s
    CPUs            => %d
    Memory Free     => %s
    Memory Usage    => %s\033[m""" % (user['name'], user['email'], user['service'], Time(), Time(user['time']), Sysinfo.Hostname,  __version__.split()[1], Sysinfo.Kernel, Sysinfo.CPUs, Sysinfo.mem_free, Sysinfo.MemPerc)

    except KeyboardInterrupt as e:
        print "捕获到终止信号，程序非正常退出! %s" % e
        sys.exit(1)
